const Koa = require("koa");
const Router = require("koa-router");
const views = require("koa-views");
const static = require("koa-static");
const koaBody = require("koa-body");
const jwt = require("jsonwebtoken");
let data = require("./data/data.json");
const koajwt = require("koa-jwt");  //校验token是否正确
let app = new Koa();
let router = new Router();
app.use(koaBody());
app.use(views(__dirname+"/views"));
app.use(static(__dirname+"/static"));
// 加载登录页面
router.get("/login",async ctx=>{
   await ctx.render("login.html");
});
// 检测是否登录
router.post("/checkUser",async ctx=>{
   let info = {};
      if(ctx.request.body.username=="张三" && ctx.request.body.pwd=='123'){
         info.status = 1;
         info.data = "登录成功";
        let token =  jwt.sign({
            name: "名字参数" 
        }, 'my_token', { expiresIn: '2h' });
         // 返还token，服务签发一个token返还给前端
         info.token = token;
      }else{
         info.status = 0;
         info.data = "登录失败";
      }
      /* 
      "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoi5ZCN5a2X5Y-C5pWwIiwiaWF0IjoxNjUzNjQxODg5LCJleHAiOjE2NTM2NDkwODl9.PYS5w-g98AgyR4MYK-fmbULDZcVPJU7lU7zb13Y8xPY"
      */
      ctx.body = info;
});



// jwt校验 校验 前端头部携带的token是否正确
router.get("/getdata",async ctx=>{
   let resdata =  JSON.parse(JSON.stringify(data)).splice(0,5);
   ctx.body = resdata
});
router.get("/getdetail",koajwt({secret:"my_token"}),async ctx=>{
    let id = ctx.query.id;
      console.log(id);
    let res =  JSON.parse(JSON.stringify(data)).filter(item=>item.id==id)[0];
   ctx.body = res;
});

router.get("/getpagedata",koajwt({secret:"my_token"}),async ctx=>{
   // 获取当前的页码 p
   let p = ctx.query.p;
   console.log(p);
   // p 1 ----> 0,5
   // p 2 ----> 6,5
   // p  ---- (p-1)*5 ,5
   let resdata =  JSON.parse(JSON.stringify(data)).splice((p-1)*5,5);
   ctx.body = resdata;
});


router.get("/getfetchdata",async ctx=>{
   ctx.body = {
      info:"fetch请求的数据",
      status:1
   }
});
app.use(router.routes());
app.listen(8989);

// 作业：1.复习 2.拖拽方块 --->2个页面的方块拖拽同步